package com.myproject.adapter;

import java.util.List;

import com.myproject.model.Coupon;
import com.myproject.source.R;
import com.myproject.source.image.ImageLoader;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CouponAdapter extends ArrayAdapter<Coupon> {
	private final Activity activity;
	private final List<Coupon> coupons;
	public ImageLoader imageLoader;

	public CouponAdapter(Activity activity, List<Coupon> objects) {
		super(activity, R.layout.coupon_list_item, objects);
		this.activity = activity;
		this.coupons = objects;
		imageLoader = new ImageLoader(activity.getApplicationContext());
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		View rowView = convertView;
		CouponView couponView = null;

		if (rowView == null) {
			// Get a new instance of the row layout view
			LayoutInflater inflater = activity.getLayoutInflater();
			rowView = inflater.inflate(R.layout.coupon_list_item, null);

			// Hold the view objects in an object,
			// so they don't need to be re-fetched
			couponView = new CouponView();
			couponView.name = (TextView) rowView.findViewById(R.id.name);
			couponView.code = (TextView) rowView.findViewById(R.id.code);
			couponView.endDate = (TextView) rowView.findViewById(R.id.endDate);
			couponView.thumb = (ImageView) rowView.findViewById(R.id.image);
			// Cache the view objects in the tag,
			// so they can be re-accessed later
			rowView.setTag(couponView);
		} else {
			couponView = (CouponView) rowView.getTag();
		}

		// Transfer the stock data from the data object
		// to the view objects
		Coupon currentcoupon = (Coupon) coupons.get(position);
		couponView.name.setText(currentcoupon.getName());
		couponView.code.setText(currentcoupon.getCode());
		couponView.endDate.setText(currentcoupon.getEndDate());

		couponView.thumb.setContentDescription(currentcoupon.getName());
		imageLoader.DisplayImage(currentcoupon.getImageUrl(), couponView.thumb);
		return rowView;
	}

	protected static class CouponView {
		protected TextView name;
		protected TextView code;
		protected TextView endDate;
		protected ImageView thumb;
	}
}
